#!/bin/sh /etc/rc.common

USE_PROCD=1
START=60

PX5G_BIN="/usr/sbin/px5g"
OPENSSL_BIN="/usr/bin/openssl"

OUI_HTTPD_CERT="/etc/oui-httpd.crt"
OUI_HTTPD_KEY="/etc/oui-httpd.key"

generate_keys() {
	local cfg="$1"
	local key="$2"
	local crt="$3"
	local days bits country state location organization commonname

	config_get days       "$cfg" days
	config_get bits       "$cfg" bits
	config_get country    "$cfg" country
	config_get state      "$cfg" state
	config_get location   "$cfg" location
	config_get organization "$cfg" organization
	config_get commonname "$cfg" commonname
	config_get key_type   "$cfg" key_type
	config_get ec_curve   "$cfg" ec_curve

	# Prefer px5g for certificate generation (existence evaluated last)
	local GENKEY_CMD=""
	local KEY_OPTS="rsa:${bits:-2048}"
	local UNIQUEID=$(dd if=/dev/urandom bs=1 count=4 | hexdump -e '1/1 "%02x"')
	[ "$key_type" = "ec" ] && KEY_OPTS="ec -pkeyopt ec_paramgen_curve:${ec_curve:-P-256}"
	[ -x "$OPENSSL_BIN" ] && GENKEY_CMD="$OPENSSL_BIN req -x509 -sha256 -outform der -nodes"
	[ -x "$PX5G_BIN" ] && GENKEY_CMD="$PX5G_BIN selfsigned -der"
	[ -n "$GENKEY_CMD" ] && {
		$GENKEY_CMD \
			-days ${days:-730} -newkey ${KEY_OPTS} -keyout "${OUI_HTTPD_KEY}.new" -out "${OUI_HTTPD_CERT}.new" \
			-subj /C="${country:-ZZ}"/ST="${state:-Somewhere}"/L="${location:-Unknown}"/O="${organization:-OpenWrt$UNIQUEID}"/CN="${commonname:-OpenWrt}"
		sync
		mv "${OUI_HTTPD_KEY}.new" "${OUI_HTTPD_KEY}"
		mv "${OUI_HTTPD_CERT}.new" "${OUI_HTTPD_CERT}"
	}
}

start_service() {
	[ -s "$OUI_HTTPD_CERT" -a -s "$OUI_HTTPD_KEY" ] || {
		config_load oui
		config_foreach generate_keys cert
	}

	procd_open_instance
	procd_set_param command /usr/sbin/oui-httpd
	procd_set_param respawn
	procd_close_instance
}

service_triggers() {
	procd_add_reload_trigger "oui"
}
